package com.suishoupai.xmb.service;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSONObject;
import com.suishoupai.xmb.exception.XmbException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class BaiduMapService {
    private static final Log log = LogFactory.getLog(BaiduMapService.class);
    @Value("${baidu.map.ak}")
    private String ak;

    @Autowired
    private HttpService httpService;

    public String getAk() {
        return ak;
    }

    public String getAddressName(Double latitude, Double longitude) {
        try {
            String result = httpService.get("http://api.map.baidu.com/geocoder/v2/?coordtype=gcj02ll&location=" + latitude + "," + longitude + "&output=json&pois=0&ak=" + ak);
            log.info(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getIntValue("status") != 0) {
                throw XmbException.newError(result);
            }
            jsonObject = JSONObject.parseObject(jsonObject.getString("result"));
            return jsonObject.getString("formatted_address");
        } catch (XmbException e) {
            e.printStackTrace();
            log.error("逆地理编码失败" + latitude + "," + longitude, e);
        }
        return "";
    }
}
